var app = getApp();
var util = require('../../utils/util.js');
Page({
  data: {
    tabbar: {},
    height: "",
    url: "",
    empClass: 0,
    showStatus: "",
    token: "",
    indexData: "",
    time: "",
    teamAchievementTitle: "",
    delBtnWidth: 160,
    isScroll: true,
    windowHeight: 0,
    data: [],
    newData: [],
    agentBonusAmount: {},
    name: "",
    addtellThree: {
      addtellHidden: false, //弹出框显示/隐藏
  },
  },
  modalCancel: function () {
    //弹出框取消操作
    this.setData({
      addtellThree: {
            addtellHidden: false,
        }
    })
},
addtell: function(e) {
  console.log(e,"0000")
  let that = this
  let id = e.currentTarget.dataset.id
  if(e.currentTarget.dataset.index != 0) {
  util.https(app.globalData.api + "/applet/partner/findAgent/" + id, "GET", {},
  function (data) {
    if (data.code == 200) {
      console.log(data)
      that.setData({
        addtellData: data.data,
        addtellThree: {
          addtellHidden: true
      }
      })
    } else {
      wx.showToast({
        title: data.message,
        icon: 'none'
      })
    }
  })
}
},
    // 分享
    onShareAppMessage: function (res) {
      var that = this;
      return {
          title: '贷投狗小程序',
          path: 'pages/partner/partner',
          success: function (res) {
              that.shareClick();
          },
          fail: function (res) {
          }
      }
  },
  onLoad: function (options) {
    app.editTabbar();
    this.setData({
      token: wx.getStorageSync('token'),
    })
    let teamPartnerStatus =  wx.getStorageSync("teamPartnerStatus")
    if(teamPartnerStatus == 1) {
    wx.setNavigationBarTitle({
      title: '合伙人'
    })
  } else {
    wx.setNavigationBarTitle({
      title: '经纪人'
    })
  }
    var that = this
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取年份  
    var Y = date.getFullYear();
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var time = Y + "-" + M
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: res.windowHeight + 20,
          windowHeight: res.windowHeight
        })
      }
    })
    let status = wx.getStorageSync('empClass')
    that.setData({
      empClass: status,
      token: wx.getStorageSync('token'),
      time: time
    })
    // this.status()
  },
  onShow: function () {
    this.setData({
      empClass: wx.getStorageSync('empClass'),
      token: wx.getStorageSync('token')
    })
    if (this.data.token) {
      this.status()
    } else {
      wx.showModal({
        title: '提示',
        content: '请先登录后查看',
        showCancel: true,//是否显示取消按钮
        cancelText: "取消",//默认是“取消”
        confirmText: "去登录",
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            wx.switchTab({
              url: '/pages/index/index',
            })
          } else {
            //点击确定
            wx.redirectTo({
              url: '/pages/account/login',
            })
          }
        },
      })
    }
  },
  // 点击拨打电话
  makePhoneCall: function () {
    let phoneNumber = this.data.addtellData.phoneNumber
    if(phoneNumber) {
    wx.makePhoneCall({
      phoneNumber: phoneNumber,
      success:function(){
        console.log('拨打成功')
      },
      fail:function(){
        console.log('拨打失败')
      }
    })
  }
  },
  // 状态判断
  status: function () {
    let that = this
    let status = wx.getStorageSync('empClass')
    let isJoinTeam = wx.getStorageSync('isJoinTeam')
    let teamPartnerStatus = wx.getStorageSync('teamPartnerStatus')
    if (status == 0) {
      that.getList() //内部员工
    } else {
      that.indexList(that.data.time) //非内部员工
    }
    if (teamPartnerStatus == 1 && !isJoinTeam) {
      that.setData({
        showStatus: 1
      })//合伙人
    }
    if (teamPartnerStatus == 0 && isJoinTeam) {
      that.setData({
        showStatus: 2
      }) //合伙人下的经纪人
      util.https(app.globalData.api + "/app/auto/empName/" + isJoinTeam, "GET", {},
        function (data) {
          if (data.code == 200) {
            that.setData({
              name: data.data
            })
          } else {
            util.toolTip(that, data.message)
          }
        }
      )
    }
    if ((teamPartnerStatus == 0 || !teamPartnerStatus) && !isJoinTeam) {
      that.setData({
        showStatus: 3
      }) //独立经纪人
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this.status()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  saveImageToPhotosAlbum: function () {
    // 保存图片
    let that = this;
    wx.getSetting({
        success: function(res){
            //不存在相册授权
            if (!res.authSetting['scope.writePhotosAlbum']){
              wx.openSetting({
                success:()=>{
                
                }
            })
                wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: function(){
                        that.savePhoto();
                    },
                    fail: function(err){
                        wx.showToast({
                            title: '授权失败',
                          })
                        }
                })
            }else{
                that.savePhoto(); 
            }
        }
    })

},
savePhoto: function () {
    const ctx = wx.createCanvasContext('myCanvas')
    wx.getImageInfo({
      src: this.data.url,
      success(res) {
        ctx.drawImage("../../images/index/canvas.png", 0, 0, wx.getSystemInfoSync().windowWidth,667)
        ctx.drawImage(res.path, (wx.getSystemInfoSync().windowWidth - 220) / 2, 320, 220, 220)
        ctx.draw(true, setTimeout(function () {
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function (res) {
              console.log(res)
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'none'
                  })
                },
                fail: () => {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          })
        }, 100))
      },
      fail (){
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })

  },
  // 二维码图片数据
  getList: function () {
    if (this.data.token) {
      var that = this
      util.https(app.globalData.api + "/applet/partner/getInviteCode", "GET", {},
        function (data) {
          if (data.code == 200) {
            that.setData({
              url: data.data
            })
          } else {
            util.toolTip(that, data.message)
          }
        }
      )
    }
  },
  // 联系管家
  // contact: function () {
  //   let current = "https://yun.xssbdc.com/group1/M00/00/00/rBiDGl8fzn-ANwfFAACgbfZf-UU573.jpg"  //
  //   wx.previewImage({
  //     current: current,
  //     urls: [current]
  //   })
  // },
  // 用户状态数据
  indexList: function (time) {
    if (this.data.token) {
      let that = this
      util.https(app.globalData.api + "/applet/partner/index?time=" + time, "GET", {},
        function (data) {
          if (data.code == 200) {
            if (data.data) {
              that.setData({
                indexData: data.data,
                teamAchievement: data.data.teamAchievement,
                agentBonusAmount: data.data.agentBonusAmount
              })
            }
            if (data.data == null) {
              that.setData({
                indexData: [],
                teamAchievement: [],
              })
            }
            if (data.data && data.data.teamAchievement.length > 0) {
              that.data.teamAchievement.forEach((item) => {
                item.right = 0
              })
              that.setData({
                teamAchievementTitle: "团队成员",
                data: that.data.teamAchievement
              })
            } else {
              that.setData({
                teamAchievementTitle: "当月暂无团队成员"
              })
            }
          } else {
            wx.showModal({
              title: '警告',
              content: data.message,
              showCancel: false,
              confirmText: '确定',
            })
            // util.toolTip(that, data.message)
          }
        }
      )
    }
  },
  ewm: function () {
    wx.navigateTo({
      url: '/pages/ewmCode/ewmCode',
    })
  },
  jjrewm: function() {
    util.https(app.globalData.api + "/applet/partner/applyTeam", "POST", {},
    function (data) {
      if (data.code == 200) {
        wx.navigateTo({
          url: '/pages/ewmCode/ewmCode',
        })
      } else {
        wx.showToast({
          title: data.message,
          icon: "none"
        })
      }
    })
  },
  getDateTime: function (e) {
    this.setData({
      time: e.detail.value
    })
    this.indexList(this.data.time)
  },
  // 左滑删除
  drawStart: function (e) {
    console.log(e,"99")
    if (e.currentTarget.dataset.index != 0) {
      var touch = e.touches[0]
      for (var index in this.data.data) {
        var item = this.data.data[index]
        item.right = 0
      }
      this.setData({
        data: this.data.data,
        startX: touch.clientX,
      })
    }
  },
  drawMove: function (e) {
    if (e.currentTarget.dataset.index != 0) {
      var touch = e.touches[0]
      var item = this.data.data[e.currentTarget.dataset.index]
      var disX = this.data.startX - touch.clientX
      if (disX >= 20) {
        if (disX > this.data.delBtnWidth) {
          disX = this.data.delBtnWidth
        }
        item.right = disX + 120
        this.setData({
          isScroll: false,
          data: this.data.data
        })
      } else {
        item.right = 0
        this.setData({
          isScroll: true,
          data: this.data.data
        })
      }
    }
  },
  drawEnd: function (e) {
    if (e.currentTarget.dataset.index != 0) {
      var item = this.data.data[e.currentTarget.dataset.index]
      if (item.right >= this.data.delBtnWidth / 2) {
        item.right = this.data.delBtnWidth + 80
        this.setData({
          isScroll: true,
          data: this.data.data,
        })
      } else {
        item.right = 0
        this.setData({
          isScroll: true,
          data: this.data.data,
        })
      }
    }
  },
  delItem: function (e) {
    let that = this
    let id = e.currentTarget.dataset.id
    let name = e.currentTarget.dataset.name
    wx.showModal({
      title: '删除成员',
      content: '确定要删除成员' + '"' + name + '"' + '?',
      showCancel: true,
      cancelText: "取消",
      confirmText: "确定",
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          util.https(app.globalData.api + "/applet/partner/deleteAgent/" + id, "DELETE", {},
            function (data) {
              console.log(data)
              if (data.code == 200) {
                wx.showToast({
                  title: data.message,
                  icon: "none"
                })
                that.indexList(that.data.time)
              } else {
                util.toolTip(that, data.message)
              }
            })
        }
      }
    })
  },
  // 升级合伙人
  promotionPartner: function () {
    util.https(app.globalData.api + "/applet/partner/applyPartner", "GET", {},
      function (data) {
        console.log(data)
        if (data.data == true) {
          wx.showModal({
            title: '提示',
            content: '您已成功获取申请合伙人资格，是否申请',
            showCancel: true,//是否显示取消按钮
            cancelText: "取消",//默认是“取消”
            confirmText: "确定",
            success: function (res) {
              if (res.cancel) {
              } else {
                //点击确定
                util.https(app.globalData.api + "/applet/partner/updateApplyStatus", "PUT", {},
                  function (data) {
                    console.log(data)
                    if (data.code == 200) {
                      wx.showModal({
                        title: '提示',
                        content: data.message,
                        showCancel: false,//是否显示取消按钮
                        confirmText: "确定",
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: data.message,
                        showCancel: false,//是否显示取消按钮
                        confirmText: "确定",
                      })
                    }
                  }
                )
              }
            },
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '暂无申请资格',
            showCancel: false,//是否显示取消按钮
            confirmText: "确定",
          })
        }
      })
  },
})